#include "stdafx.h"
#include "PlayerDataLua.h"
#include "ProgressLua.h"
#include "FormDataLua.h"

namespace PlayerDataLua
{

	bool push(lua_State* L, PlayerData* pPlayerData)
	{
		PlayerData** pp = (PlayerData**)lua_newuserdata(L, sizeof(PlayerData*));
		*pp = pPlayerData;
		luaL_getmetatable(L, "woe.PlayerData");
		if (lua_istable(L, -1))
		{
			lua_setmetatable(L, -2);
			return true;
		}
		else
		{
			LOG_ERROR("Failed to push PlayerData to lua, metatable not found!");
			return false;
		}
	}

	PlayerData* getUserData(lua_State* L)
	{
		PlayerData**pp = (PlayerData**)luaL_checkudata(L, 1, "woe.PlayerData");
		if (pp==NULL)
		{
			return NULL;
		}
		else
		{
			return *pp;
		}
	}

	int getFormData(lua_State* L)
	{
		PlayerData* pPlayerData = getUserData(L);
		if (pPlayerData)
		{
			Forms* data = pPlayerData->getFormData();
			if (data)
			{
				FormDataLua::push(L, data);
				return 1;
			}
		}
		return 0;
	}

	int getProgressData(lua_State* L)
	{
		PlayerData* pPlayerData = getUserData(L);
		if (pPlayerData)
		{
			Progress* data = pPlayerData->getProgressData();
			if (data)
			{
				ProgressLua::push(L, data);
				return 1;
			}
		}
		return 0;
	}

	static const luaL_Reg PlayerData_funcs[] = {
		{"getForm", getFormData},
		{"getProgress", getProgressData},
		{"getFormData", getFormData},
		{"getProgressData", getProgressData},
		{NULL, NULL}
	};


	int libaray(lua_State* L)
	{
		luaL_newmetatable(L, "woe.PlayerData");
		// fill member list into metatable
		luaL_register(L, NULL, PlayerData_funcs);

		// metatable.__index = metatable
		lua_pushstring(L, "__index");
		lua_pushvalue(L, -2);
		lua_settable(L, -3);

		return 0;
	}

} // end of PlayerData lua
